<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body" v-if="cartList.length > 0">
        <ul class="cart-list" v-for="(cart, index) in cartList" :key="cart.id">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="cart.isChecked"
              @change="changeChecked(cart)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cart.imgUrl" />
            <div class="item-msg">
              {{ cart.skuName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cart.cartPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="addOrSub(0, cart)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="cart.skuNum"
              minnum="1"
              class="itxt"
              @change="checkSkuNum(cart, $event)"
            />
            <a href="javascript:void(0)" class="plus" @click="addOrSub(1, cart)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cart.skuPrice * cart.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="javascript:void(0)"
              class="sindelet"
              @click="delOneProd(cart.skuId, index)"
              >删除</a
            >
            <br />
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool" v-if="cartList.length > 0">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="isAllChecked" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:void(0)" @click="delBatchProds">删除选中的商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ totalProds }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <a
            class="sum-btn"
            href="javascript:void(0)"
            @click="$router.push('/trade')"
            >结算</a
          >
        </div>
      </div>
    </div>
    <div
      style="
        margin: 0 auto;
        text-align: center;
        height: 300px;
        line-height: 300px;
      "
      v-if="cartList.length === 0"
    >
      <h1>购物车空空如也!</h1>
    </div>
  </div>
</template>

<script>
import { skuNumReg } from "@/utils";
export default {
  name: "ShopCart",
  data() {
    return {
      cartList: [],
    };
  },
  computed: {
    // 是否全选
    isAllChecked: {
      get() {
        return (
          this.cartList.every((item) => item.isChecked) &&
          this.cartList.length > 0
        );
      },
      async set(val) {
        const valNum = val * 1;
        const idList = this.cartList.map((item) => item.skuId);
        await this.$API.reqChangeAllChecked(valNum, idList);
        this.cartList.forEach((item) => (item.isChecked = valNum));
      },
    },
    // 商品总数
    totalProds() {
      //pre=item.isChecked?pre+item.skuNum:pre
      return this.cartList.reduce(
        (pre, item) => (pre = item.isChecked ? pre + item.skuNum : pre),
        0
      );
    },
    // 商品总价
    totalPrice() {
      return this.cartList.reduce(
        (pre, item) =>
          (pre = item.isChecked ? pre + item.skuNum * item.skuPrice : pre),
        0
      );
    },
  },
  methods: {
    // 获取数据
    async getData() {
      const { data } = await this.$API.reqGetCartList();
      this.cartList = data[0]?.cartInfoList || [];
      this.skuNumLock && (this.skuNumLock = false);
    },
    // 是否勾选
    async changeChecked(cart) {
      const { skuId, isChecked } = cart;
      const val = Number(!isChecked);
      await this.$API.reqChangeIsChecked(skuId, val);
      cart.isChecked = val;
    },
    // 删除单个商品
    async delOneProd(id, index) {
      if (window.confirm("确定删除?")) {
        await this.$API.reqDelOneProd(id);
        this.cartList.splice(index, 1);
      }
    },
    // 批量删除
    async delBatchProds() {
      if (window.confirm("确定删除选中的商品?")) {
        const ids = this.cartList.reduce(
          (pre, cur) => (cur.isChecked ? pre.push(cur.skuId) && pre : pre),
          []
        );
        await this.$API.reqDelBatchProds(ids);
        this.getData();
      }
    },
    // 校验数量
    async checkSkuNum({ skuId, skuNum }, e) {
      if (this.skuNumLock) return;
      const { value } = e.target;
      if (skuNumReg.test(value)) {
        this.skuNumLock = true;
        const num = value - skuNum;
        await this.$API.reqAddProdOrder(skuId, num);
        this.getData();
      } else {
        this.skuNumLock = true;
        const newVal = parseInt(value);
        if (isNaN(newVal) || newVal < 1) e.target.value = newVal;
        if (newVal > 200) {
          await this.$API.reqAddProdOrder(skuId, 200 - skuNum);
          this.getData();
        }
      }
    },
    // 加或减
    async addOrSub(state, cart) {
      if (this.skuNumLock) return;
      this.skuNumLock = true;
      state
        ? cart.skuNum < 200 &&
          (await this.$API.reqAddProdOrder(cart.skuId, 1)) &&
          this.getData()
        : cart.skuNum > 1 &&
          (await this.$API.reqAddProdOrder(cart.skuId, -1)) &&
          this.getData();
    },
  },
  mounted() {
    this.getData();
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 31px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;
        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
          text-decoration: none;
          &hover {
            color: white !important;
          }
        }
      }
    }
  }
}
</style>
